package org.dromara.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.dromara.business.constant.BusinessConstants;
import org.dromara.business.domain.Goods;
import org.dromara.business.domain.vo.BusinessConfigVo;
import org.dromara.business.domain.vo.GoodsVo;
import org.dromara.business.domain.vo.SellerGoodsVo;
import org.dromara.business.mapper.GoodsMapper;
import org.dromara.business.service.BusinessConfigService;
import org.dromara.business.service.GoodsService;
import org.dromara.business.service.RoomService;
import org.dromara.business.service.UserFlowingService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.TopUpCoreService;
import org.dromara.common.core.service.WxOrderService;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.service.ISysUserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 任务Service业务层处理
 *
 * @author zlj
 * @date 2024-08-01
 */
@RequiredArgsConstructor
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    private final GoodsMapper baseMapper;
    private final RoomService roomService;
    @Resource
    @Lazy
    private TopUpCoreService topUpCoreService;
    private final ISysUserService userService;
    private final UserFlowingService flowingService;
    private final BusinessConfigService configService;
    private final WxOrderService wxOrderService;

    /**
     * 查询任务
     */
    @Override
    public GoodsVo queryById(Long goodsId) {
        GoodsVo goodsVo = baseMapper.selectVoById(goodsId);
        BusinessConfigVo size = configService.queryById(goodsVo.getSizeId());
        BusinessConfigVo weight = configService.queryById(goodsVo.getWeightId());
        BusinessConfigVo area = configService.queryById(goodsVo.getAreaId());
        goodsVo.setMinAmount(new BigDecimal(size.getRemark()).add(new BigDecimal(weight.getRemark())).add(new BigDecimal(area.getRemark())));
        return goodsVo;
    }

    /**
     * 查询任务列表
     */
    @Override
    public TableDataInfo<GoodsVo> queryPageList(Goods bo, PageQuery pageQuery) {
        Page<Goods> page = pageQuery.build();
        LambdaQueryWrapper<Goods> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ObjectUtil.isNotNull(bo.getStatus()), Goods::getStatus, bo.getStatus());
        lqw.like(ObjectUtil.isNotNull(bo.getName()), Goods::getName, bo.getName());
        lqw.eq(ObjectUtil.isNotNull(bo.getCreateBy()), Goods::getCreateBy, LoginHelper.getUserId());
        lqw.eq(ObjectUtil.isNotNull(bo.getUserId()), Goods::getUserId, LoginHelper.getUserId());
        lqw.orderByDesc(StrUtil.isBlank(pageQuery.getOrderByColumn()), Goods::getCreateTime);
        IPage<GoodsVo> iPage = baseMapper.selectVoPage(page, lqw);
        return TableDataInfo.build(iPage);
    }

    /**
     * 查询任务列表
     */
    @Override
    public List<GoodsVo> queryList(Goods bo) {
        LambdaQueryWrapper<Goods> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Goods> buildQueryWrapper(Goods bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Goods> lqw = Wrappers.lambdaQuery();
        lqw.eq(ObjectUtil.isNotNull(bo.getGoodsId()), Goods::getGoodsId, bo.getGoodsId());
        lqw.like(StrUtil.isNotBlank(bo.getName()), Goods::getName, bo.getName());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), Goods::getStatus, bo.getStatus());
        lqw.orderByDesc(Goods::getCreateTime);
        return lqw;
    }

    /**
     * 新增任务
     */
    @Override
    public Long insertByBo(Goods add) {
        validEntityBeforeSave(add);
        SysUser user = userService.getById(LoginHelper.getUserId());
        add.setUserProfile(user.getWxAvatar());
        add.setStatus("0");
        boolean flag = baseMapper.insertOrUpdate(add);
        if (flag) {
            add.setGoodsId(add.getGoodsId());
        }
        return add.getGoodsId();
    }

    /**
     * 修改任务
     */
    @Override
    public Boolean updateByBo(Goods update) {
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Goods entity) {

    }

    /**
     * 批量删除任务
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean updateGoodsStatus(Long goodsId, Integer status, String infoDesc) {
        return this.lambdaUpdate().set(Goods::getStatus, status)
            .eq(Goods::getGoodsId, goodsId)
            .update();
    }

    @Override
    public List<SellerGoodsVo> sellerListGoods(String userId, int type) {
        return baseMapper.sellerListGoods(userId, type);
    }

    @Override
    public boolean goodsUp(Long goodsId) {
        return this.lambdaUpdate().set(Goods::getStatus, 0).eq(Goods::getGoodsId, goodsId).update();
    }

    @Override
    public Boolean takeOrders(Long goodsId) {
        //判断非骑手是否可以接单
        String isAll = configService.queryValueByKey("is_all");
        String remark = userService.getById(LoginHelper.getUserId()).getRemark();
        if (ObjectUtil.notEqual(isAll, "1")) {
            if (ObjectUtil.notEqual(remark, "骑手")) {
                throw new ServiceException("只有骑手可以抢单哦");
            }
        }
        Goods goods = this.getById(goodsId);
        if (ObjectUtil.notEqual(goods.getStatus(), "2")) {
            throw new ServiceException("任务不存在");
        }
        goods.setUserId(LoginHelper.getUserId());
        goods.setStatus("3");
        roomService.send(0L, goods.getCreateBy(), "任务<" + goods.getName() + ">已有人接, 请注意查收");
        return this.updateById(goods);
    }

    @Override
    public Boolean served(Long goodsId) {
        Goods goods = this.getById(goodsId);
        if (ObjectUtil.notEqual(goods.getUserId(), LoginHelper.getUserId())) {
            throw new ServiceException("非法操作");
        }
        if (ObjectUtil.notEqual(goods.getStatus(), "3")) {
            throw new ServiceException("非法操作");
        }
        goods.setStatus("4");
        roomService.send(0L, goods.getCreateBy(), "任务<" + goods.getName() + ">已送达, 请确认, 如有异议请在个人中心联系客服人员");
        //更新物流信息
        String isWxOrder = configService.queryValueByKey("is_wx_order");
        if (ObjectUtil.equals(isWxOrder, "1")) {
            wxOrderService.uploadShippingInfo(goods.getGoodsId());
        }
        return this.updateById(goods);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean receiving(Long goodsId) {
        Goods goods = this.getById(goodsId);
        if (ObjectUtil.notEqual(goods.getCreateBy(), LoginHelper.getUserId())) {
            throw new ServiceException("非法操作");
        }
        if (ObjectUtil.notEqual(goods.getStatus(), "4")) {
            throw new ServiceException("非法操作");
        }
        //发放佣金
        String rebate = configService.queryValueByKey("rebate");
        BigDecimal decimal = goods.getPrice().multiply(BigDecimal.ONE.subtract(new BigDecimal(rebate)));
        flowingService.addAmount(goods.getUserId(), decimal, BusinessConstants.FLOWING_TYPE_REBATE, goods.getCreateBy());
        goods.setStatus("5");
        roomService.send(0L, goods.getUserId(), "任务<" + goods.getName() + ">对方已确认收货,悬赏金已到账");
        return this.updateById(goods);
    }

    @Override
    public Boolean up(Long goodsId) {
        Goods goods = this.getById(goodsId);
        if (ObjectUtil.notEqual(goods.getCreateBy(), LoginHelper.getUserId())) {
            throw new ServiceException("非法操作");
        }
        if (ObjectUtil.equals(goods.getStatus(), "1")) {
            goods.setStatus("2");
        } else if ((ObjectUtil.equals(goods.getStatus(), "2"))) {
            goods.setStatus("1");
        } else {
            throw new ServiceException("非法操作");
        }
        return this.updateById(goods);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeGoods(Long goodsId) {
        Goods goods = this.getById(goodsId);
        if (ObjectUtil.notEqual(goods.getCreateBy(), LoginHelper.getUserId())) {
            throw new ServiceException("非法操作");
        }
        if (ObjectUtil.equals(goods.getStatus(), "0")) {
            return this.removeById(goodsId);
        } else if ((ObjectUtil.equals(goods.getStatus(), "1"))) {
            // 退款
            topUpCoreService.refundByGoodsId(goodsId);
            return this.removeById(goodsId);
        } else {
            throw new ServiceException("非法操作");
        }
    }

    @Override
    public Boolean removeByUser(Long goodsId) {
        Goods goods = this.getById(goodsId);
        if (ObjectUtil.notEqual(goods.getUserId(), LoginHelper.getUserId())) {
            throw new ServiceException("非法操作");
        }
        roomService.send(0L, goods.getCreateBy(), "您发布的任务" + goods.getName() + "对方已取消接单,已重新发布到悬赏大厅");
        return this.lambdaUpdate().set(Goods::getStatus, "2").set(Goods::getUserId, null)
            .set(Goods::getUpdateTime, new Date())
            .eq(Goods::getGoodsId, goodsId).update();
    }
}
